﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using Jaws.Core.Web.Attributes;
using Jaws.Core.Web.Entities;
using Jaws.Core.Web.Entities.Pages;

namespace Jaws.WebApp
{
    public class Global : HttpApplication
    {
        public PageCollection Pages = XmlCollectionBase<PageCollection, Page>.Load();


        public List<UserControlAttribute> PublicUserControlMembers
        {
            get
            {
                return (List<UserControlAttribute>)Application["PublicUserControlMembers"];
            }
            private set
            {
                Application["PublicUserControlMembers"] = value;
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            if (System.Web.Security.Membership.GetAllUsers().Count == 0)
            {
                System.Web.Security.Membership.CreateUser("admin", "password", "roman.clarkson@gmail.com");
            }

            if (!System.Web.Security.Roles.RoleExists("admin"))
            {
                System.Web.Security.Roles.CreateRole("admin");
                System.Web.Security.Roles.AddUserToRole("admin", "admin");
            }
            
            GetPublicUserControls();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
        }

        protected void Application_Error(object sender, EventArgs e)
        {
        }

        protected void Session_End(object sender, EventArgs e)
        {
        }

        protected void Application_End(object sender, EventArgs e)
        {
        }

        protected void GetPublicUserControls()
        {
            PublicUserControlMembers = new List<UserControlAttribute>();
            var uca = new List<UserControlAttribute>();
            Assembly asm = Assembly.GetExecutingAssembly();
            if (asm != null)
                foreach (Type t in asm.GetTypes())
                {
                    object[] attributes = t.GetCustomAttributes(typeof(UserControlAttribute), false);
                    foreach (object o in attributes)
                    {
                        if (o is UserControlAttribute)
                        {
                            uca.Add((UserControlAttribute)o);
                        }
                    }
                }

            PublicUserControlMembers = uca;
        }
    }
}